package com.molichuxing.gateway.bff.order.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.gateway.bff.order.convertor.Convert;
import com.molichuxing.gateway.bff.order.entity.request.modify.OrderTradeAuditModifyVo;
import com.molichuxing.gateway.bff.order.entity.request.modify.OrderTradeRefundModifyVo;
import com.molichuxing.gateway.bff.order.entity.response.*;
import com.molichuxing.gateway.bff.order.services.OrderBffService;
import com.molichuxing.services.business.dto.response.*;
import com.molichuxing.services.business.service.*;
import com.molichuxing.services.infrastructure.dto.request.create.MessageCenterCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.NotifyPushCreateDto;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service("orderBffService")
public class OrderBffServiceImpl implements OrderBffService {
	private static final Logger logger = LoggerFactory.getLogger(OrderBffServiceImpl.class);

	@Resource
	private OrderService orderService;

	@Resource
	private OrderBizService orderBizService;

	@Resource
	private StoreService storeService;

	@Resource
	private UserBizService userBizService;

	@Resource
	private ContractService contractService;

	@Resource
	private OrderReturnService orderReturnService;

	@Resource
	private OrderDeliveryService orderDeliveryService;

	@Resource
	private OrderAuditService orderAuditService;

	@Resource
	private OrderTradeBizService orderTradeBizService;

	@Resource
	private OrderStatusFlowService orderStatusFlowService;

	@Resource
	private VehicleBizService vehicleBizService;

	@Resource
	private UserService userService;

	@Resource
	private SmsBizService smsBizService;

	@Resource
	private NotifyPushService notifyPushService;

	@Resource
	private MessageTemplateService messageTemplateService;

	@Resource
	private MessageCenterService messageCenterService;

	/**
	 * 根据用户id获取订单信息
	 * 
	 * @param userId
	 *            用户id
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<UserOrderVo> getOrderByUser(Integer userId) throws Exception {
		List<UserOrderVo> result = null;

		List<UserOrderBizDto> userOrderBizDtoList = orderBizService.getOrderByUser(userId);
		if (userOrderBizDtoList == null || userOrderBizDtoList.isEmpty()) {
			return result;
		}

		result = new ArrayList<>();
		// 门店id集合
		List<Integer> storeIds = new ArrayList<>();
		// 车型id集合
		List<Integer> vehicleIds = new ArrayList<>();
		for (UserOrderBizDto userOrderBizDto : userOrderBizDtoList) {
			storeIds.add(userOrderBizDto.getPlaceStoreId());
			vehicleIds.add(userOrderBizDto.getVehicleId());
			result.add(Convert.toUserOrderVo(userOrderBizDto));
		}

		// 查询门店
		Map<Integer, StoreDto> storeMap = storeService.getStoreMapByIds(storeIds);
		// 查询车型名称
		Map<Integer, String> vehicleMap = vehicleBizService.getVehicleFullName(vehicleIds);
		if ((storeMap == null || storeMap.size() <= 0) && (vehicleMap == null || vehicleMap.size() <= 0)) {
			return result;
		}

		for (UserOrderVo userOrderVo : result) {
			// 门店
			StoreDto storeDto = storeMap == null ? null
					: storeMap.isEmpty() ? null : storeMap.get(userOrderVo.getPlaceStoreId());
			// 下单门店(简称)
			userOrderVo.setPlaceStoreName(storeDto == null ? null : storeDto.getShortName());
			// 车型名称
			userOrderVo.setVehicleName(vehicleMap == null ? null : vehicleMap.get(userOrderVo.getVehicleId()));
		}

		return result;
	}

	/**
	 * 根据车辆id获取订单信息
	 * 
	 * @param carId
	 *            车辆id
	 * @return
	 */
	@Override
	public List<CarOrderVo> getOrderByCar(Integer carId) throws Exception {
		List<CarOrderVo> result = null;

		List<CarOrderBizDto> carOrderBizDtoList = orderBizService.getOrderByCar(carId);
		if (carOrderBizDtoList == null || carOrderBizDtoList.isEmpty()) {
			return result;
		}

		result = new ArrayList<>();
		// 门店id集合
		List<Integer> storeIds = new ArrayList<>();
		// 用户id集合
		List<Integer> userIds = new ArrayList<>();
		for (CarOrderBizDto carOrderBizDto : carOrderBizDtoList) {
			storeIds.add(carOrderBizDto.getDeliveryStoreId());
			userIds.add(carOrderBizDto.getUserId());
			result.add(Convert.toCarOrderVo(carOrderBizDto));
		}

		// 查询门店
		Map<Integer, StoreDto> storeMap = storeService.getStoreMapByIds(storeIds);
		// 查询用户
		Map<Integer, UserBizDto> userMap = userBizService.getUsers(userIds);
		if ((storeMap == null || storeMap.size() <= 0) && (userMap == null || userMap.size() <= 0)) {
			return result;
		}

		for (CarOrderVo carOrderVo : result) {
			// 门店
			StoreDto storeDto = storeMap == null ? null
					: storeMap.isEmpty() ? null : storeMap.get(carOrderVo.getDeliveryStoreId());
			// 下单门店(简称)
			carOrderVo.setDeliveryStoreName(storeDto == null ? null : storeDto.getShortName());
			// 用户
			UserBizDto userBizDto = userMap == null ? null
					: userMap.isEmpty() ? null : userMap.get(carOrderVo.getUserId());
			// 用户账号
			carOrderVo.setUserName(userBizDto == null ? null : userBizDto.getName());
			carOrderVo.setRealName(userBizDto == null ? null : userBizDto.getRealName());
			carOrderVo.setUserPhone(userBizDto == null ? null : userBizDto.getPhone());
			carOrderVo.setIdNumber(userBizDto == null ? null : userBizDto.getIdNumber());
		}

		return result;
	}

	/**
	 * 根据订单号获取订单单据或合同信息
	 * 
	 * @param orderCode
	 *            订单号
	 * @param documentType
	 *            类型 1：单据，2：合同
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<OrderContractVo> getOrderContract(Long orderCode, DocumentTypeEnum documentType) throws Exception {
		List<OrderContractVo> result = null;

		List<ContractDto> contractDtos = contractService.getContractList(orderCode, documentType);
		if (contractDtos == null || contractDtos.isEmpty()) {
			return result;
		}
		// 判断类型
		if (documentType == null) {
			result = Convert.toOrderContractVo(contractDtos);
		} else if (DocumentTypeEnum.CONTRACT.equals(documentType)) {
			result = Convert.toOrderContractVo(contractDtos);
		} else if (DocumentTypeEnum.SHEET.equals(documentType)) {
			result = new ArrayList<>();
			// 查询订单信息
			OrderBizDto orderBizDto = orderBizService.getOrder(orderCode);

			// 查询门店顾问和车辆里程
			for (ContractDto contractDto : contractDtos) {
				OrderContractVo vo = Convert.toOrderContractVo(contractDto);
				if (contractDto.getContractType() == ContractTypeEnum.MILEAGE_BAG_CAR_CONTRACT.getValue()) {
					// 交车单
					OrderDeliveryDto orderDeliveryDto = orderDeliveryService.getOrderDelivery(orderCode);
					if (orderDeliveryDto != null) {
						vo.setContractTypeStr("交车单");
						vo.setContractName("订阅里程服务交车单");
						vo.setSignedTime(contractDto.getSignedTime());
						vo.setSalesmanName(orderDeliveryDto.getSalesmanName());
					}
				} else if (contractDto.getContractType() == ContractTypeEnum.MILEAGE_BAG_RETURN_CAR.getValue()) {
					// 还车单
					OrderReturnDto orderReturnDto = orderReturnService.getOrderReturn(orderCode);
					if (orderReturnDto != null) {
						vo.setContractTypeStr("还车单");
						vo.setContractName("订阅里程服务还车单");
						vo.setSignedTime(contractDto.getSignedTime());
						vo.setSalesmanName(orderReturnDto.getSalesmanName());
					}
				}

				result.add(setMileage(vo, orderBizDto, contractDto.getContractType()));
			}

			// 查询验车单据
			// List<CarCheckDto> carCheckDtos =
			// carCheckBizService.getCheckByOrderCode(orderCode);
			// if (carCheckDtos != null && !carCheckDtos.isEmpty()) {
			// for (CarCheckDto carCheckDto : carCheckDtos) {
			// if (carCheckDto.getType() == 2) {
			// OrderContractVo vo = new OrderContractVo();
			// vo.setContractTypeStr("验车单");
			// vo.setContractName("订阅里程服务验车单");
			// vo.setMileage(carCheckDto.getMileage());
			// vo.setSignedTime(carCheckDto.getCheckTime());
			// vo.setSalesmanName(carCheckDto.getOpName());
			// result.add(vo);
			// }
			// }
			// }
		}
		return result;
	}

	private OrderContractVo setMileage(OrderContractVo vo, OrderBizDto orderBizDto, int contractType) {
		if (OrderTypeEnum.EXCLUSIVEL.equals(orderBizDto.getType())) {
			// 专属里程订单
			OrderExclusivelBizDto orderExclusivelBizDto = (OrderExclusivelBizDto) orderBizDto;
			if (contractType == ContractTypeEnum.CAR_CONTRACT.getValue()) {
				// 交车单
				vo.setMileage(orderExclusivelBizDto.getStartMileage() == null ? null
						: new BigDecimal(orderExclusivelBizDto.getStartMileage()));
			}
		} else if (OrderTypeEnum.SUBSCRIBE.equals(orderBizDto.getType())) {
			// 订阅里程订单
			OrderSubscribeBizDto orderSubscribeBizDto = (OrderSubscribeBizDto) orderBizDto;
			if (contractType == ContractTypeEnum.MILEAGE_BAG_CAR_CONTRACT.getValue()) {
				// 交车单
				vo.setMileage(orderSubscribeBizDto.getStartMileage() == null ? null
						: new BigDecimal(orderSubscribeBizDto.getStartMileage()));
			} else if (contractType == ContractTypeEnum.MILEAGE_BAG_RETURN_CAR.getValue()) {
				// 还车单
				vo.setMileage(orderSubscribeBizDto.getSettleMileage() == null ? null
						: new BigDecimal(orderSubscribeBizDto.getSettleMileage()));
			}
		}

		return vo;

	}

	/**
	 * 订单审核
	 * 
	 * @param modifyVo
	 * @return
	 */
	@Override
	public Boolean modifyOrderAudit(OrderTradeAuditModifyVo modifyVo) {
		Boolean result = false;
		OrderAuditResultEnum auditResult = OrderAuditResultEnum.getEnum(modifyVo.getResult());
		if (OrderAuditResultEnum.REJECT.equals(auditResult) && StringUtils.isBlank(modifyVo.getReason())) {
			// 驳回时，原因不能为空
			throw new BizException("驳回原因不能为空");
		}
		result = orderTradeBizService.modifyAudit(Convert.toOrderAuditModifyBizDto(modifyVo, auditResult));
		if (result) {
			// 修改数据成功，发送消息
			pushMsg(modifyVo, auditResult);
		}

		return result;
	}

	private void pushMsg(OrderTradeAuditModifyVo modifyVo, OrderAuditResultEnum auditResult) {
		try {
			// 查询订单信息
			OrderBizDto orderBizDto = orderBizService.getOrder(modifyVo.getOrderCode());
			if (orderBizDto == null) {
				return;
			}
			Integer userId = null;
			JSONObject json = new JSONObject();
			Integer smsCode = null;
			VehicleNameBizDto vehicleName = null;
			StoreDto store = null;
			String product = null;
			MessageTemplateDto messageTemplateDto = null;
			String body = null;
			String message = null;
			if (OrderTypeEnum.EXCLUSIVEL.equals(orderBizDto.getType())) {
				// 专属订单
				OrderExclusivelBizDto orderExclusivel = (OrderExclusivelBizDto) orderBizDto;
				userId = orderExclusivel.getUserId();
				// 查询车型信息
				vehicleName = vehicleBizService.getCarByModel(orderExclusivel.getVehicleId());
				// 商品名称
				String paymentMethodStr = OrderPaymentMethodEnum.INSTALLMENT.equals(orderExclusivel.getPaymentMethod())
						? "月付" : orderExclusivel.getPaymentMethod().getName();
				product = vehicleName.getModelName() + " " + orderExclusivel.getTransportTime() + "期/"
						+ (orderExclusivel.getIsBuyback() ? "回购/" : "不回购/") + paymentMethodStr;
				json.put("product", product);
				// 订单号
				json.put("order", orderExclusivel.getOrderCode());
				if (OrderAuditResultEnum.PASS.equals(auditResult)) {
					// 通过
					smsCode = SmsTemplateEnum.ORDER_AUDIT_SMS_ONE.getValue();
					// 查询门店
					store = storeService.getStoreById(orderExclusivel.getPlaceStoreId());
					// 提车截止天数
					json.put("num", 15);
					// 门店
					json.put("store", store.getFullName());
					Map<String, MessageTemplateDto> templateMap = messageTemplateService
							.getByKey(Arrays.asList("push_order_audit_pass", "instation_order_audit_pass"));
					messageTemplateDto = templateMap.get("push_order_audit_pass");
					body = messageTemplateDto.getBody().replace("${goodsName}", product).replace("${orderCode}",
							orderExclusivel.getOrderCode() + "").replace("${store}", store.getFullName());

					message = templateMap.get("instation_order_audit_pass").getBody().replace("${goodsName}", product)
							.replace("${orderCode}", orderExclusivel.getOrderCode() + "")
							.replace("${store}", store.getFullName());
				} else {
					// 驳回
					smsCode = SmsTemplateEnum.ORDER_AUDIT_SMS_TWO.getValue();
					Map<String, MessageTemplateDto> templateMap = messageTemplateService
							.getByKey(Arrays.asList("push_order_audit_no_pass", "instation_order_audit_no_pass"));
					messageTemplateDto = templateMap.get("push_order_audit_no_pass");
					body = messageTemplateDto.getBody().replace("${goodsName}", product).replace("${orderCode}",
							orderExclusivel.getOrderCode() + "");

					message = templateMap.get("instation_order_audit_no_pass").getBody()
							.replace("${goodsName}", product)
							.replace("${orderCode}", orderExclusivel.getOrderCode() + "");
				}
			} else if (OrderTypeEnum.SUBSCRIBE.equals(orderBizDto.getType())) {
				// 订阅订单
				OrderSubscribeBizDto orderSubscribe = (OrderSubscribeBizDto) orderBizDto;
				userId = orderSubscribe.getUserId();
				// 查询车型信息
				vehicleName = vehicleBizService.getCarByModel(orderSubscribe.getVehicleId());
				// 商品名称
				product = vehicleName.getModelName() + " " + orderSubscribe.getTransportTime() + "个月/"
						+ orderSubscribe.getBaseMileage() + "公里, " + orderSubscribe.getPackageMileage() + "公里";
				json.put("product", product);
				// 订单号
				json.put("order", orderSubscribe.getOrderCode());
				if (OrderAuditResultEnum.PASS.equals(auditResult)) {
					// 通过
					smsCode = SmsTemplateEnum.ORDER_AUDIT_SMS_THREE.getValue();
					// 查询门店
					store = storeService.getStoreById(orderSubscribe.getPlaceStoreId());
					// 门店
					json.put("store", store.getFullName());

					Map<String, MessageTemplateDto> templateMap = messageTemplateService
							.getByKey(Arrays.asList("push_order_audit_pass", "instation_order_audit_pass"));
					messageTemplateDto = templateMap.get("push_order_audit_pass");
					body = messageTemplateDto.getBody().replace("${goodsName}", product)
							.replace("${orderCode}", orderSubscribe.getOrderCode() + "")
							.replace("${store}", store.getFullName());

					message = templateMap.get("instation_order_audit_pass").getBody().replace("${goodsName}", product)
							.replace("${orderCode}", orderSubscribe.getOrderCode() + "")
							.replace("${store}", store.getFullName());
				} else {
					// 驳回
					smsCode = SmsTemplateEnum.ORDER_AUDIT_SMS_FOVE.getValue();
					Map<String, MessageTemplateDto> templateMap = messageTemplateService
							.getByKey(Arrays.asList("push_order_audit_no_pass", "instation_order_audit_no_pass"));
					messageTemplateDto = templateMap.get("push_order_audit_no_pass");
					body = messageTemplateDto.getBody().replace("${goodsName}", product).replace("${orderCode}",
							orderSubscribe.getOrderCode() + "");

					message = templateMap.get("instation_order_audit_no_pass").getBody()
							.replace("${goodsName}", product)
							.replace("${orderCode}", orderSubscribe.getOrderCode() + "");
				}
			} else {
				logger.error("订单(" + modifyVo.getOrderCode() + ")审核完成发送消息异常，订单类型(" + orderBizDto.getType() + ")错误");
			}
			// 查询用户信息
			UserDto userDto = userService.getUser(userId);
			// 发送短信
			try {
				smsBizService.sendMessage(userDto.getPhone(), smsCode,
						json.toJSONString(), null);
			} catch (Exception e) {
				logger.error("订单(" + modifyVo.getOrderCode() + ")审核完成发送短信异常", e);
			}
			// 发送推送
			try {
				NotifyPushCreateDto notifyPush = new NotifyPushCreateDto(Arrays.asList(userDto.getPhone()),
						messageTemplateDto.getSubject(), messageTemplateDto.getSubject(), body, body, null, "");
				notifyPushService.notifyPushByAlias(notifyPush);
			} catch (Exception e) {
				logger.error("订单(" + modifyVo.getOrderCode() + ")审核完成发送消息异常：", e);
			}
			// 保存消息
			MessageCenterCreateDto messageCenterCreateDto = new MessageCenterCreateDto();
			messageCenterCreateDto.setUserId(userDto.getId());
			messageCenterCreateDto.setTitle("订单审核结果通知");
			messageCenterCreateDto.setMessage(message);
			messageCenterCreateDto.setType(MessageCenterTypeEnum.ORDER_AUDIT_RESULTS_NOTICE.getValue());
			messageCenterCreateDto.setStatus(MessageCenterStatusEnum.UNREAD.getValue());

			messageCenterService.createMessageCenter(messageCenterCreateDto);

		} catch (Exception e) {
			String msg = "订单(" + modifyVo.getOrderCode() + ")审核完成发送消息异常：";
			logger.error(msg, e);
		}
	}

	/**
	 * 获取订单审核信息
	 * 
	 * @param orderCode
	 *            订单号
	 * @return
	 */
	@Override
	public OrderAuditVo getOrderAudit(Long orderCode) {
		return Convert.toOrderAuditVo(orderAuditService.getOrderAudit(orderCode));
	}

	/**
	 * 订单交易退款
	 * 
	 * @param modifyVo
	 * @return
	 */
	@Override
	public Boolean modifyOrderTradeRefund(OrderTradeRefundModifyVo modifyVo) {
		return orderTradeBizService.modifyRefund(Convert.toOrderTradeRefundModifyBizDto(modifyVo));
	}

	/**
	 * 获取订单交易退款信息
	 * 
	 * @param orderCode
	 *            订单号
	 * @return
	 * @throws Exception
	 */
	@Override
	public OrderTradeRefundVo getOrderTradeRefund(Long orderCode) throws Exception {
		OrderTradeRefundVo result = null;
		OrderDto orderDto = orderService.getOrder(orderCode);
		if (orderDto == null) {
			return result;
		}
		if (OrderTypeEnum.EXCLUSIVEL.equals(orderDto.getType())) {
			// 专属订单
			List<OrderExclusivelStatusFlowDto> statusFlows = orderStatusFlowService
					.getExclusivelOrderStatusFlow(orderCode);
			if (statusFlows == null || statusFlows.isEmpty()) {
				return result;
			}
			result = new OrderTradeRefundVo();
			for (OrderExclusivelStatusFlowDto statusFlowDto : statusFlows) {
				if (OrderExclusivelStatusEnum.TRADE_REFUND.equals(statusFlowDto.getOrderStatus())) {
					// 退款中
					result.setIssueId(statusFlowDto.getOrderUserId());
					result.setIssueName(statusFlowDto.getOrderUserName());
					result.setIssueTime(statusFlowDto.getOrderModifiedTime());
				} else if (OrderExclusivelStatusEnum.TRADE_FINISH.equals(statusFlowDto.getOrderStatus())) {
					// 已完成
					result.setFinishId(statusFlowDto.getOrderUserId());
					result.setFinishName(statusFlowDto.getOrderUserName());
					result.setFinishTime(statusFlowDto.getOrderModifiedTime());
				}
			}
		} else if (OrderTypeEnum.SUBSCRIBE.equals(orderDto.getType())) {
			// 订阅订单
			List<OrderSubscribeStatusFlowDto> statusFlows = orderStatusFlowService
					.getSubscribeOrderStatusFlow(orderCode);
			if (statusFlows == null || statusFlows.isEmpty()) {
				return result;
			}
			result = new OrderTradeRefundVo();
			for (OrderSubscribeStatusFlowDto statusFlowDto : statusFlows) {
				if (OrderSubscribeStatusEnum.TRADE_REFUND.equals(statusFlowDto.getOrderStatus())) {
					// 退款中
					result.setIssueId(statusFlowDto.getOrderUserId());
					result.setIssueName(statusFlowDto.getOrderUserName());
					result.setIssueTime(statusFlowDto.getOrderModifiedTime());
				} else if (OrderSubscribeStatusEnum.TRADE_FINISH.equals(statusFlowDto.getOrderStatus())) {
					// 已完成
					result.setFinishId(statusFlowDto.getOrderUserId());
					result.setFinishName(statusFlowDto.getOrderUserName());
					result.setFinishTime(statusFlowDto.getOrderModifiedTime());
				}
			}
		}
		return result;
	}
}
